<template>
  <el-dialog v-model="isShowExport" :width="600" center :show-close="false">
    <template #header>
      <title-view title="导出列表字段" />
    </template>
    <div class="transfer-container" v-loading="isLoading">
      <div class="check-container">
        <div class="check-all-container">
          <el-checkbox v-model="isLeftCheckedAll" :indeterminate="isLeftIndeterminate" @change="handelLeftCheckedAll"
            >可选字段
          </el-checkbox>
        </div>
        <div class="list-container">
          <div class="search-box">
            <el-input
              v-model.trim="searchVal"
              placeholder="请输入关键词"
              :suffix-icon="Search"
              @input="handleSearch"
              clearable
              @clear="handleClear"
            ></el-input>
          </div>
          <template v-if="leftList.length">
            <div class="left-list-content">
              <div class="list-container-item" :class="{ 'item-active': item.checked }" v-for="item in leftList">
                <el-checkbox
                  v-model="item.checked"
                  :label="item.title"
                  :value="item.fieldId"
                  :key="item.fieldId"
                  :disabled="fixedFields.includes(item.fieldId)"
                  @change="handleLeftChecked($event, item)"
                >
                  <!--                  :disabled="item.fieldId == 'customer_name'"-->
                  {{ item.title }}
                </el-checkbox>
              </div>
            </div>
          </template>
          <el-empty v-else />
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handelCancel">取消</el-button>
        <el-button type="primary" @click="handelConfirm">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref, getCurrentInstance, toRaw } from "vue";
import { documentFlow } from "@/utils/downFile";
import _ from "lodash";
import { dayjs } from "element-plus";
import { customerExportHeader, customerExport, groupList } from "@/apis/clientManager";
import { Search } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  tableBodyParams: {
    type: Object,
    default: () => ({})
  }
});
const emit = defineEmits(["update:modelValue"]);

/**
 * 获取分类名称
 */
const exportFileName = ref("");
const fixedNameArr = [
  { customerGroupId: "0", customerGroupName: "全部" },
  { customerGroupId: "1", customerGroupName: "今日新增" },
  { customerGroupId: "2", customerGroupName: "本周新增" },
  { customerGroupId: "3", customerGroupName: "今日跟进" },
  { customerGroupId: "4", customerGroupName: "本周跟进" }
];
const groupNameArr = ref([]);
const getGroupList = async () => {
  try {
    const { data } = await groupList();
    const res = data || [];
    const handleResult = res.map(item => {
      return {
        customerGroupName: item.customerGroupName,
        customerGroupId: item.customerGroupId
      };
    });
    groupNameArr.value = [...handleResult, ...fixedNameArr];
    const currentGroup = groupNameArr.value.find(item => item.customerGroupId == props.tableBodyParams.customerGroupId);
    exportFileName.value = currentGroup?.customerGroupName || "导出";
  } catch (err) {
    console.log(err);
  }
};

/**
 * 导出列表字段
 */
const isLoading = ref(false);
const searchVal = ref("");
// 源数据
const sourceList = ref([]);
// 固定字段
const fixedFields = ref(["customer_name"]);
// 表头字段列表（默认选中导出字段）
const getTableHeaderSort = async () => {
  try {
    isLoading.value = true;
    const { data } = await customerExportHeader();
    leftList.value =
      data?.map(item => {
        return {
          ...item,
          checked: !!item.isSelect
        };
      }) || [];
    const filterNotFixField = leftList.value.filter(item => item.checked && !fixedFields.value.includes(item.fieldId));
    leftSelected.value = _.cloneDeep(filterNotFixField);
    sourceList.value = _.cloneDeep(leftList.value);
    isLeftCheckedAll.value = leftSelected.value.length === sourceList.value.length;
    isLeftIndeterminate.value = !isLeftCheckedAll.value;
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
  }
};

/**
 * 导出
 */
const isShowExport = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});
/**
 * 搜索
 * @param e
 */
const getSearchData = e => {
  leftList.value = e ? sourceList.value.filter(item => item.title.includes(e)) : _.cloneDeep(sourceList.value);
  const filterSelected = leftList.value.filter(item => item.checked);
  isLeftCheckedAll.value = filterSelected.length === leftList.value.length;
  isLeftIndeterminate.value = filterSelected.length ? !isLeftCheckedAll.value : false;
};
const handleSearch = _.debounce(getSearchData, 500);
const handleClear = () => {
  searchVal.value = "";
  getSearchData("");
};

const isLeftCheckedAll = ref(true);
const isLeftIndeterminate = ref(false);
// 渲染列表数据
const leftList = ref([]);
// 已选中的数据
const leftSelected = ref([]);
// const handelLeftCheckedAll = e => {
//   leftList.value.forEach(item => {
//     item.checked = e;
//   });
//   leftSelected.value = e ? _.cloneDeep(leftList.value);
// };
// 全选
const handelLeftCheckedAll = e => {
  isLeftCheckedAll.value = e;
  isLeftIndeterminate.value = e && false;
  if (!searchVal.value) {
    console.log("是全部数据");
    leftList.value.map(item => {
      item.checked = fixedFields.value.includes(item.fieldId) ? true : e;
    });
    sourceList.value.map(item => {
      item.checked = fixedFields.value.includes(item.fieldId) ? true : e;
    });
    const filterFixedField = sourceList.value.filter(item => !fixedFields.value.includes(item.fieldId));
    leftSelected.value = e ? _.cloneDeep(filterFixedField) : [];
  } else {
    console.log("选中数据,不是全部数据");
    const notAllListClone = JSON.parse(JSON.stringify(leftList.value)); //当前的搜索出来的数据
    const isSelected = [];
    const notSelected = [];
    notAllListClone.map(item => {
      if (item.checked) {
        isSelected.push(item);
      } else {
        notSelected.push(item);
      }
    });
    leftList.value.map(item => {
      item.checked = fixedFields.value.includes(item.fieldId) ? true : e;
    });
    sourceList.value.map(item => {
      item.checked = fixedFields.value.includes(item.fieldId) ? true : e;
    });

    if (e) {
      leftSelected.value = [...leftSelected.value, ...notSelected];
    } else {
      const deleteIndex = isSelected.map(item => item.fieldIds);
      if (deleteIndex.length > 0) {
        for (let i = deleteIndex.length - 1; i >= 0; i--) {
          leftSelected.value.splice(deleteIndex[i], 1);
        }
      }
    }
  }
};
// 单选
const handleLeftChecked = (e, data) => {
  if (e) {
    const isCheckedAll = leftList.value.every(item => item.checked);
    isLeftIndeterminate.value = !isCheckedAll;
    isLeftCheckedAll.value = isCheckedAll;
    //isCheckedAll:仅针对于搜索结果全选
    if (isCheckedAll && leftList.value.length === sourceList.value.length) {
      leftSelected.value = _.cloneDeep(leftList.value);
    } else {
      leftSelected.value.push(_.cloneDeep(data));
    }
  } else {
    const filterSelected = leftList.value.filter(item => item.checked);
    const dataIndex = leftSelected.value.findIndex(item => item.fieldId === data.fieldId);
    dataIndex !== -1 && leftSelected.value.splice(dataIndex, 1);
    isLeftCheckedAll.value = false;
    isLeftIndeterminate.value = filterSelected.length;
  }
};

const handelConfirm = async () => {
  const customerArr = sourceList.value.filter(item => fixedFields.value.includes(item.fieldId));
  const cloneLeftSelected = _.cloneDeep(leftSelected.value);
  const toRowFixFieldArr = customerArr?.map(item => toRaw(item));
  const handleSubmitData = [...cloneLeftSelected, ...toRowFixFieldArr];
  const ids = handleSubmitData.map(item => item.fieldId);
  try {
    isLoading.value = true;
    const { groupType, customerGroupId, lost } = proxy.tableBodyParams;
    const res = await customerExport({ fieldIds: ids, groupType, customerGroupId, lost });
    isLoading.value = false;
    const fileName = exportFileName.value + "-" + dayjs().format("YYYYMMDDHHmmss");
    documentFlow(res, fileName, "xlsx");
    // proxy.$modal.msgSuccess("保存成功");
    isShowExport.value = false;
  } catch (err) {
    isLoading.value = false;
  }
};
const handelCancel = () => {
  isShowExport.value = false;
};

getTableHeaderSort();
getGroupList();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";

.transfer-container {
  @include mixin.flex-align;
  margin-bottom: 30px;

  .check-container {
    @include mixin.flex-column;
    width: 100%;
    height: 360px;
    border-radius: 6px;
    border: 1px solid #dcdcdc;
    position: relative;

    .search-box {
      width: calc(100% - 20px);
      position: absolute;
      left: 10px;
      z-index: 99;
      padding-top: 20px;
      background: #fff;
    }
  }

  .check-all-container {
    @include mixin.flex-align;
    height: 48px;
    padding: 0 16px;
    border-bottom: 1px solid #e7e7e7;
  }

  .list-container {
    flex: 1;
    overflow-y: auto;
    padding: 0 8px 30px 8px;

    .left-list-content {
      padding-top: 60px;
    }

    &-item {
      @include mixin.flex-between;
      @include mixin.flex-align;
      margin-top: 10px;
      padding: 0 8px;
    }

    .item-active {
      background-color: #f2f3ff;
      border-radius: 3px;
    }

    .drag-handle {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }
  }
  :deep(.el-checkbox) {
    display: inline-flex;
    height: auto;
  }
  :deep(.el-checkbox__label) {
    //width: 100px;
    //overflow: hidden;
    //white-space: nowrap;
    //text-overflow: ellipsis;
    white-space: wrap;
    line-height: 1.6;
  }
}

:deep(.el-empty__image) {
  width: 30%;
}

.dialog-footer {
  button {
    width: 90px;
    height: 38px;
  }
}
</style>
